package pmr.core.remover;

import java.util.Set;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;

public class UnusedMethodRemover {

	private final ICompilationUnit compilationUnit;

	public UnusedMethodRemover(ICompilationUnit compilationUnit) {
		this.compilationUnit = compilationUnit;
	}

	public void remove(Set<IMethod> methodsToRemove) throws JavaModelException,
			MalformedTreeException, BadLocationException {
		String source = compilationUnit.getSource();
		Document document = new Document(source);
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setSource(compilationUnit);
		CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
		astRoot.recordModifications();
		TypeDeclaration typeDeclaration = (TypeDeclaration) astRoot.types()
				.get(0);

		MethodDeclaration[] methods = typeDeclaration.getMethods();
		for (MethodDeclaration m : methods) {
			int pos = m.getStartPosition();
			IJavaElement element = compilationUnit.getElementAt(pos);
			if (element instanceof IMethod && methodsToRemove.contains(element)) {
				m.delete();
			}
		}
		TextEdit edits = astRoot.rewrite(document, compilationUnit
				.getJavaProject().getOptions(true));
		edits.apply(document);
		String newSource = document.get();
		compilationUnit.getBuffer().setContents(newSource);
		compilationUnit.getBuffer().save(null, true);
	}
}
